const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const SECRET = 'djo1ij2eijoqi';
const { User } = require('../db/model/userModel'); // 引入
const mailSender = require('../utils/mail.js');
const isdebug = true;

let codes = {}; // 我们这个例子 验证码就放着内存中了。正常开发也可以放redis 或者 数据库内

// 默认首页：选择登录或注册
router.get('/', (req, res, next) => {
  // console.log(req.session);
  let username = req.session.username;
  console.log(username);
  // If there is a session named user that means the use is logged in. so we redirect him to home page by using /home route below
  if (username) {
    res.redirect('/main');
    return;
  }
  // IF not we just send the index page.
  res.render('./public/views/index');
});

// // index页
// router.get('/index', (req, res, next) => {
//   res.render('public/views/index');
// });

// 登录表单
router.get('/login', (req, res, next) => {
  res.render('public/views/login');
});

// 注册表单
router.get('/register', (req, res, next) => {
  res.render('./public/views/register');
});

// 登录
router.post('/api/login', async (req, res) => {
  console.log(req.body)
  // 获取数据
  let us = req.body.username
  let ps = req.body.password
  var user = await User.findOne({username: us})
  if(!user){
    return res.status(422).send({
        message: '用户名不存在'
    });//客户端提交数据有问题
  }
  var isPasswordValid = require('bcrypt').compareSync(ps, user.password)
  if(!isPasswordValid){
    return res.status(422).send({
      message: '密码无效'
    })
  };
  //生成token
  const token = jwt.sign(
    {
      id: String(user._id),//密码不要放进来，放一个唯一的东西就可以了
    }, 
    SECRET,
    {
      expiresIn: "1h"
    }
  );
  // console.log(token);
  req.session.token = token;
  // console.log(req.session.token);
  res.set({
    'Authotization': `Bearer ${token}`
  })
  // // res.send({
  // //     user,
  // //     token
  // // });
  res.redirect('../main');
  // res.redirect('./profile');
  // res.render('./public/views/main', { token: token });
});

// 发送邮件验证码
router.post('/api/getmailcode', (req, res) => {
  let mail = req.body.username
  console.log(mail);
  if (mail) {
    let code = parseInt(Math.random() * 10000) // 随机验证码
    codes[mail] = code
    console.log(codes)
    if (isdebug) {
      console.log("已成功发送验证码到邮箱");
    }
    else {
      mailSender.send(mail, code, (result) => {
        // res.send(result.message);
        console.log("已成功发送验证码到邮箱");
      });
    }

  } else {
    res.send("发送失败")
  }
})

// 注册
router.post('/api/register', async (req, res) => {
  // 获取数据
  let us = req.body.username
  let ps = req.body.password
  let code = req.body.code

  if (us && ps && code) {
    // 判断验证码是否ok
    if (!(codes[us] === Number(code))) { // 邮箱作为用户名
      return res.send({ err: -4, msg: '验证码错误' })
    }
    // console.log(req.body);
    const user = await User.create({
      username: us,
      password: ps
    }, (err, doc)=>{
      if(err){
        res.send("邮箱已存在")
      }
      // res.send(doc)
    })
    res.redirect('./login');
  }
});

// 获取数据库中users数据
router.get('/api/users' , async (req , res)=>{
  const users = await User.find();
  res.send(users)
});

//auth中间件
const auth = async (req, res, next) => {
  // const raw = String(req.headers.authorization).split(' ').pop();
  // console.log(req.session.token);
  const raw = req.session.token;
  if(!raw){
    res.render('public/views/login')
  }
  const {id} = jwt.verify(raw, SECRET);
  await User.findById(id, (err, doc)=>{
    if(err){
      res.redirect('/')
    }
    else{
      req.user = doc;
      next();
    }
  });
}

// 测试auth页
router.get('/api/profile', auth, async (req, res) => {
  res.send(req.user);
})
// app.get('/api/orders', auth, async (req, res) => {
//     const orders = await Order.find().where({
//         user: req.user
//     });
//     res.send(orders);
// })

// 主页
router.get('/main', auth, async (req, res) => {
    const user = req.user;
    res.send(`当前用户： ${user.username}`)
  }
);


module.exports = router